<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学习笔记 - AI知识管理中心</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-markup.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-css.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&family=Noto+Serif+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Noto Sans SC', sans-serif;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            min-height: 100vh;
        }
        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .note-item {
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .note-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        }
        .note-item.active {
            border-left: 4px solid #3b82f6;
            background: rgba(59, 130, 246, 0.05);
        }
        .editor-container {
            min-height: 400px;
        }
        .code-block {
            background: #1e293b;
            border-radius: 8px;
            padding: 1rem;
            margin: 1rem 0;
            overflow-x: auto;
        }
        .tag {
            transition: all 0.2s ease;
        }
        .tag:hover {
            transform: scale(1.05);
        }
        .search-highlight {
            background: rgba(59, 130, 246, 0.2);
            padding: 2px 4px;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="fixed top-0 left-0 right-0 z-50 glass-card">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center space-x-3">
                    <div class="w-8 h-8 bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg flex items-center justify-center">
                        <span class="text-white font-bold text-sm">AI</span>
                    </div>
                    <h1 class="text-xl font-bold text-gray-800">知识管理中心</h1>
                </div>
                <div class="flex space-x-6">
                    <a href="index.html" class="text-gray-600 hover:text-blue-600 transition-colors">仪表板</a>
                    <a href="notes.html" class="text-blue-600 font-medium border-b-2 border-blue-600 pb-1">学习笔记</a>
                    <a href="news.html" class="text-gray-600 hover:text-blue-600 transition-colors">AI资讯</a>
                    <a href="settings.html" class="text-gray-600 hover:text-blue-600 transition-colors">设置</a>
                </div>
            </div>
        </div>
    </nav>

    <div class="pt-16 min-h-screen">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <!-- 页面标题 -->
            <div class="mb-8">
                <h1 class="text-3xl font-bold text-gray-800 mb-2">学习笔记</h1>
                <p class="text-gray-600">记录和管理您的AI学习心得</p>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
                <!-- 侧边栏 -->
                <div class="lg:col-span-1">
                    <div class="glass-card rounded-2xl p-6 shadow-lg">
                        <!-- 搜索框 -->
                        <div class="mb-6">
                            <input type="text" id="search-input" placeholder="搜索笔记..." 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>

                        <!-- 分类筛选 -->
                        <div class="mb-6">
                            <h3 class="text-lg font-semibold text-gray-800 mb-3">分类</h3>
                            <div class="space-y-2" id="category-filter">
                                <button class="filter-btn w-full text-left px-3 py-2 rounded-lg bg-blue-100 text-blue-800" data-category="all">
                                    全部笔记 <span class="float-right" id="count-all">0</span>
                                </button>
                                <button class="filter-btn w-full text-left px-3 py-2 rounded-lg hover:bg-gray-100 transition-colors" data-category="AI大模型">
                                    AI大模型 <span class="float-right" id="count-ai">0</span>
                                </button>
                                <button class="filter-btn w-full text-left px-3 py-2 rounded-lg hover:bg-gray-100 transition-colors" data-category="编程工具">
                                    编程工具 <span class="float-right" id="count-coding">0</span>
                                </button>
                                <button class="filter-btn w-full text-left px-3 py-2 rounded-lg hover:bg-gray-100 transition-colors" data-category="技术架构">
                                    技术架构 <span class="float-right" id="count-arch">0</span>
                                </button>
                            </div>
                        </div>

                        <!-- 标签云 -->
                        <div class="mb-6">
                            <h3 class="text-lg font-semibold text-gray-800 mb-3">标签</h3>
                            <div class="flex flex-wrap gap-2" id="tag-cloud">
                                <!-- 标签将通过JavaScript动态添加 -->
                            </div>
                        </div>

                        <!-- 新建笔记按钮 -->
                        <button onclick="createNewNote()" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg font-medium transition-colors">
                            新建笔记
                        </button>
                    </div>
                </div>

                <!-- 笔记列表 -->
                <div class="lg:col-span-1">
                    <div class="glass-card rounded-2xl p-6 shadow-lg">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-lg font-semibold text-gray-800">笔记列表</h3>
                            <select id="sort-select" class="px-3 py-1 border border-gray-300 rounded-lg text-sm">
                                <option value="newest">最新创建</option>
                                <option value="oldest">最早创建</option>
                                <option value="updated">最近更新</option>
                            </select>
                        </div>
                        
                        <div id="notes-list" class="space-y-3 max-h-96 overflow-y-auto">
                            <!-- 笔记列表将通过JavaScript动态添加 -->
                        </div>
                    </div>
                </div>

                <!-- 编辑器区域 -->
                <div class="lg:col-span-2">
                    <div class="glass-card rounded-2xl p-6 shadow-lg">
                        <div id="editor-container">
                            <!-- 编辑模式 -->
                            <div id="edit-mode" class="hidden">
                                <div class="mb-4">
                                    <input type="text" id="note-title-input" placeholder="笔记标题..." 
                                           class="w-full text-2xl font-bold border-none outline-none bg-transparent placeholder-gray-400">
                                </div>
                                
                                <div class="mb-4">
                                    <select id="note-category-input" class="px-3 py-2 border border-gray-300 rounded-lg">
                                        <option value="AI大模型">AI大模型</option>
                                        <option value="编程工具">编程工具</option>
                                        <option value="技术架构">技术架构</option>
                                        <option value="算法研究">算法研究</option>
                                        <option value="其他">其他</option>
                                    </select>
                                </div>

                                <div class="mb-4">
                                    <input type="text" id="note-tags-input" placeholder="添加标签，用逗号分隔..." 
                                           class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                </div>

                                <div class="editor-container">
                                    <textarea id="note-content-input" placeholder="开始记录您的学习心得..." 
                                              class="w-full h-96 p-4 border border-gray-300 rounded-lg resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"></textarea>
                                </div>

                                <div class="flex justify-between items-center mt-6">
                                    <div class="flex space-x-3">
                                        <button onclick="saveCurrentNote()" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg transition-colors">
                                            保存笔记
                                        </button>
                                        <button onclick="cancelEdit()" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg transition-colors">
                                            取消
                                        </button>
                                    </div>
                                    <button onclick="deleteCurrentNote()" class="text-red-500 hover:text-red-700 transition-colors">
                                        删除笔记
                                    </button>
                                </div>
                            </div>

                            <!-- 预览模式 -->
                            <div id="preview-mode" class="hidden">
                                <div class="mb-4">
                                    <h2 id="note-title-display" class="text-2xl font-bold text-gray-800 mb-2"></h2>
                                    <div class="flex items-center space-x-4 text-sm text-gray-500">
                                        <span id="note-category-display"></span>
                                        <span id="note-date-display"></span>
                                    </div>
                                </div>

                                <div id="note-tags-display" class="mb-4">
                                    <!-- 标签将通过JavaScript动态添加 -->
                                </div>

                                <div id="note-content-display" class="prose max-w-none">
                                    <!-- 内容将通过JavaScript动态添加 -->
                                </div>

                                <div class="mt-6 flex space-x-3">
                                    <button onclick="editCurrentNote()" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg transition-colors">
                                        编辑笔记
                                    </button>
                                    <button onclick="exportNote()" class="bg-green-600 hover:bg-green-700 text-white px-6 py-2 rounded-lg transition-colors">
                                        导出笔记
                                    </button>
                                </div>
                            </div>

                            <!-- 空状态 -->
                            <div id="empty-state" class="text-center py-12">
                                <div class="w-16 h-16 bg-gray-200 rounded-full mx-auto mb-4 flex items-center justify-center">
                                    <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                                    </svg>
                                </div>
                                <h3 class="text-lg font-medium text-gray-800 mb-2">开始记录您的学习之旅</h3>
                                <p class="text-gray-600 mb-4">创建您的第一篇学习笔记，记录AI学习的每一个重要时刻</p>
                                <button onclick="createNewNote()" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg transition-colors">
                                    新建笔记
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let notes = JSON.parse(localStorage.getItem('notes')) || [];
        let currentNote = null;
        let currentFilter = 'all';
        let currentTag = null;

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeNotes();
            loadNotesList();
            updateCategoryCounts();
            generateTagCloud();
            bindEventListeners();
        });

        // 初始化笔记数据
        function initializeNotes() {
            if (notes.length === 0) {
                notes = [
                    {
                        id: 1,
                        title: 'DeepSeek V3.3学习笔记',
                        content: `# DeepSeek V3.3 新特性分析

## 核心改进
- **编程能力大幅提升**：在前端代码生成方面实现质的飞跃
- **MIT许可证**：支持商业项目自由集成和修改
- **6850亿参数**：MoE架构，激活参数约370亿

## 性能表现
新版本在多个基准测试中表现出色：

\`\`\`javascript
// 示例代码：使用DeepSeek API
const response = await fetch('https://api.deepseek.com/v3/chat/completions', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY'
    },
    body: JSON.stringify({
        model: 'deepseek-v3-0324',
        messages: [{ role: 'user', content: '生成一个React组件' }]
    })
});
\`\`\`

## 实际体验
经过测试，DeepSeek V3.3在以下方面表现优异：
1. 代码生成的准确性和可用性
2. 中文理解和生成能力
3. 长文本处理性能
4. 响应速度（60 tokens/秒）

## 总结
DeepSeek V3.3的发布标志着开源AI模型的重大进步，为开发者提供了高性价比的选择。`,
                        category: 'AI大模型',
                        tags: ['DeepSeek', '编程', '开源', 'V3.3'],
                        createdAt: new Date().toISOString(),
                        updatedAt: new Date().toISOString()
                    },
                    {
                        id: 2,
                        title: 'Claude Code 2.0新功能详解',
                        content: `# Claude Code 2.0 深度体验

## Hooks功能介绍
Claude Code 2.0引入了Hooks功能，这是AI编程助手的重要突破：

### PreToolUse钩子
在调用工具前自动执行命令，例如：
- 验证bash命令的安全性
- 检查文件路径是否有效
- 自动格式化代码

### PostToolUse钩子
工具调用成功后执行的操作：
- 自动运行测试
- 代码风格检查
- 生成文档

### Notification钩子
发送通知的功能：
- 任务完成提醒
- 错误报警
- 进度更新

## 实际应用场景
\`\`\`bash
# 配置文件示例
{
    "hooks": {
        "PreToolUse": [
            "validate-command",
            "check-security"
        ],
        "PostToolUse": [
            "run-tests",
            "format-code"
        ]
    }
}
\`\`\`

## 性能提升
- 编程效率提升3倍
- 支持更长的复杂任务
- 终端与IDE无缝协作

## 个人体验
使用Hooks功能后，开发流程变得更加自动化和可靠。`,
                        category: '编程工具',
                        tags: ['Claude', '编程助手', 'Hooks', '自动化'],
                        createdAt: new Date().toISOString(),
                        updatedAt: new Date().toISOString()
                    },
                    {
                        id: 3,
                        title: 'AI编程工具对比分析',
                        content: `# AI编程工具全面对比

## 主流工具概览
当前市场上的AI编程工具主要包括：

### 1. Claude Code 2.0
- **优势**：Hooks功能，自主性强
- **适用场景**：复杂项目开发
- **定价**：每百万token $15输出

### 2. GitHub Copilot
- **优势**：集成度高，响应快速
- **适用场景**：日常编码辅助
- **定价**：$10/月

### 3. Trae + Claude 3.7
- **优势**：免费使用最强编程模型
- **适用场景**：个人开发者
- **定价**：免费

### 4. Cursor
- **优势**：专为AI编程设计
- **适用场景**：AI原生开发
- **定价**：$20/月

## 性能对比
\`\`\`python
# 性能测试代码示例
def benchmark_code_generation(tool, prompt):
    """测试代码生成性能"""
    start_time = time.time()
    code = tool.generate(prompt)
    generation_time = time.time() - start_time
    
    # 测试代码质量
    quality_score = evaluate_code_quality(code)
    
    return {
        'generation_time': generation_time,
        'quality_score': quality_score,
        'lines_of_code': len(code.split('\\n'))
    }
\`\`\`

## 选择建议
根据团队规模、项目复杂度和预算选择合适的工具。`,
                        category: '编程工具',
                        tags: ['对比分析', '编程工具', 'AI助手', '性能测试'],
                        createdAt: new Date().toISOString(),
                        updatedAt: new Date().toISOString()
                    }
                ];
                localStorage.setItem('notes', JSON.stringify(notes));
            }
        }

        // 绑定事件监听器
        function bindEventListeners() {
            // 搜索功能
            document.getElementById('search-input').addEventListener('input', function(e) {
                searchNotes(e.target.value);
            });

            // 分类筛选
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const category = this.dataset.category;
                    filterByCategory(category);
                    
                    // 更新按钮状态
                    document.querySelectorAll('.filter-btn').forEach(b => {
                        b.classList.remove('bg-blue-100', 'text-blue-800');
                        b.classList.add('hover:bg-gray-100');
                    });
                    this.classList.add('bg-blue-100', 'text-blue-800');
                    this.classList.remove('hover:bg-gray-100');
                });
            });

            // 排序功能
            document.getElementById('sort-select').addEventListener('change', function() {
                sortNotes(this.value);
            });
        }

        // 加载笔记列表
        function loadNotesList() {
            const notesList = document.getElementById('notes-list');
            let filteredNotes = notes;

            // 应用筛选
            if (currentFilter !== 'all') {
                filteredNotes = filteredNotes.filter(note => note.category === currentFilter);
            }

            if (currentTag) {
                filteredNotes = filteredNotes.filter(note => note.tags.includes(currentTag));
            }

            notesList.innerHTML = filteredNotes.map(note => `
                <div class="note-item p-4 bg-white rounded-lg border border-gray-200 ${currentNote && currentNote.id === note.id ? 'active' : ''}" onclick="selectNote(${note.id})">
                    <h4 class="font-medium text-gray-800 mb-2 truncate">${note.title}</h4>
                    <p class="text-sm text-gray-600 mb-2 line-clamp-2">${note.content.substring(0, 100)}...</p>
                    <div class="flex items-center justify-between">
                        <span class="text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded-full">${note.category}</span>
                        <span class="text-xs text-gray-500">${formatDate(note.updatedAt)}</span>
                    </div>
                    <div class="flex flex-wrap gap-1 mt-2">
                        ${note.tags.slice(0, 3).map(tag => `
                            <span class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded">${tag}</span>
                        `).join('')}
                        ${note.tags.length > 3 ? `<span class="text-xs text-gray-500">+${note.tags.length - 3}</span>` : ''}
                    </div>
                </div>
            `).join('');
        }

        // 选择笔记
        function selectNote(id) {
            currentNote = notes.find(note => note.id === id);
            if (currentNote) {
                showPreviewMode();
                loadNotesList(); // 重新加载以更新选中状态
            }
        }

        // 创建新笔记
        function createNewNote() {
            currentNote = {
                id: Date.now(),
                title: '',
                content: '',
                category: 'AI大模型',
                tags: [],
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            };
            showEditMode();
        }

        // 显示编辑模式
        function showEditMode() {
            document.getElementById('edit-mode').classList.remove('hidden');
            document.getElementById('preview-mode').classList.add('hidden');
            document.getElementById('empty-state').classList.add('hidden');

            if (currentNote) {
                document.getElementById('note-title-input').value = currentNote.title;
                document.getElementById('note-category-input').value = currentNote.category;
                document.getElementById('note-tags-input').value = currentNote.tags.join(', ');
                document.getElementById('note-content-input').value = currentNote.content;
            }
        }

        // 显示预览模式
        function showPreviewMode() {
            document.getElementById('edit-mode').classList.add('hidden');
            document.getElementById('preview-mode').classList.remove('hidden');
            document.getElementById('empty-state').classList.add('hidden');

            if (currentNote) {
                document.getElementById('note-title-display').textContent = currentNote.title;
                document.getElementById('note-category-display').textContent = currentNote.category;
                document.getElementById('note-date-display').textContent = `更新于 ${formatDate(currentNote.updatedAt)}`;
                
                // 显示标签
                const tagsContainer = document.getElementById('note-tags-display');
                tagsContainer.innerHTML = currentNote.tags.map(tag => `
                    <span class="tag inline-block px-3 py-1 bg-blue-100 text-blue-800 text-sm rounded-full cursor-pointer" onclick="filterByTag('${tag}')">${tag}</span>
                `).join('');

                // 显示内容（支持Markdown格式）
                const contentContainer = document.getElementById('note-content-display');
                contentContainer.innerHTML = renderMarkdown(currentNote.content);
                
                // 高亮代码块
                Prism.highlightAll();
            }
        }

        // 显示空状态
        function showEmptyState() {
            document.getElementById('edit-mode').classList.add('hidden');
            document.getElementById('preview-mode').classList.add('hidden');
            document.getElementById('empty-state').classList.remove('hidden');
        }

        // 保存当前笔记
        function saveCurrentNote() {
            if (!currentNote) return;

            const title = document.getElementById('note-title-input').value.trim();
            const category = document.getElementById('note-category-input').value;
            const tags = document.getElementById('note-tags-input').value.split(',').map(tag => tag.trim()).filter(tag => tag);
            const content = document.getElementById('note-content-input').value.trim();

            if (!title || !content) {
                alert('请输入笔记标题和内容');
                return;
            }

            currentNote.title = title;
            currentNote.category = category;
            currentNote.tags = tags;
            currentNote.content = content;
            currentNote.updatedAt = new Date().toISOString();

            // 检查是否是新笔记
            const existingIndex = notes.findIndex(note => note.id === currentNote.id);
            if (existingIndex === -1) {
                notes.unshift(currentNote);
            } else {
                notes[existingIndex] = currentNote;
            }

            localStorage.setItem('notes', JSON.stringify(notes));
            loadNotesList();
            updateCategoryCounts();
            generateTagCloud();
            showPreviewMode();
            showNotification('笔记保存成功！');
        }

        // 取消编辑
        function cancelEdit() {
            if (currentNote && currentNote.title) {
                showPreviewMode();
            } else {
                showEmptyState();
                currentNote = null;
            }
        }

        // 编辑当前笔记
        function editCurrentNote() {
            showEditMode();
        }

        // 删除当前笔记
        function deleteCurrentNote() {
            if (!currentNote) return;

            if (confirm('确定要删除这篇笔记吗？')) {
                notes = notes.filter(note => note.id !== currentNote.id);
                localStorage.setItem('notes', JSON.stringify(notes));
                currentNote = null;
                loadNotesList();
                updateCategoryCounts();
                generateTagCloud();
                showEmptyState();
                showNotification('笔记删除成功！');
            }
        }

        // 搜索笔记
        function searchNotes(query) {
            const notesList = document.getElementById('notes-list');
            let filteredNotes = notes;

            if (query.trim()) {
                filteredNotes = notes.filter(note => 
                    note.title.toLowerCase().includes(query.toLowerCase()) ||
                    note.content.toLowerCase().includes(query.toLowerCase()) ||
                    note.tags.some(tag => tag.toLowerCase().includes(query.toLowerCase()))
                );
            }

            // 应用其他筛选
            if (currentFilter !== 'all') {
                filteredNotes = filteredNotes.filter(note => note.category === currentFilter);
            }

            if (currentTag) {
                filteredNotes = filteredNotes.filter(note => note.tags.includes(currentTag));
            }

            notesList.innerHTML = filteredNotes.map(note => {
                const highlightedTitle = highlightSearchTerm(note.title, query);
                const highlightedContent = highlightSearchTerm(note.content.substring(0, 100), query);
                
                return `
                    <div class="note-item p-4 bg-white rounded-lg border border-gray-200 ${currentNote && currentNote.id === note.id ? 'active' : ''}" onclick="selectNote(${note.id})">
                        <h4 class="font-medium text-gray-800 mb-2 truncate">${highlightedTitle}</h4>
                        <p class="text-sm text-gray-600 mb-2 line-clamp-2">${highlightedContent}...</p>
                        <div class="flex items-center justify-between">
                            <span class="text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded-full">${note.category}</span>
                            <span class="text-xs text-gray-500">${formatDate(note.updatedAt)}</span>
                        </div>
                        <div class="flex flex-wrap gap-1 mt-2">
                            ${note.tags.slice(0, 3).map(tag => `
                                <span class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded">${tag}</span>
                            `).join('')}
                            ${note.tags.length > 3 ? `<span class="text-xs text-gray-500">+${note.tags.length - 3}</span>` : ''}
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 高亮搜索词
        function highlightSearchTerm(text, term) {
            if (!term.trim()) return text;
            const regex = new RegExp(`(${term})`, 'gi');
            return text.replace(regex, '<span class="search-highlight">$1</span>');
        }

        // 按分类筛选
        function filterByCategory(category) {
            currentFilter = category;
            currentTag = null;
            loadNotesList();
        }

        // 按标签筛选
        function filterByTag(tag) {
            currentTag = tag;
            currentFilter = 'all';
            
            // 更新分类按钮状态
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.classList.remove('bg-blue-100', 'text-blue-800');
                btn.classList.add('hover:bg-gray-100');
            });
            document.querySelector('[data-category="all"]').classList.add('bg-blue-100', 'text-blue-800');
            document.querySelector('[data-category="all"]').classList.remove('hover:bg-gray-100');
            
            loadNotesList();
        }

        // 排序笔记
        function sortNotes(sortBy) {
            switch (sortBy) {
                case 'newest':
                    notes.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
                    break;
                case 'oldest':
                    notes.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
                    break;
                case 'updated':
                    notes.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt));
                    break;
            }
            loadNotesList();
        }

        // 更新分类计数
        function updateCategoryCounts() {
            const counts = {
                all: notes.length,
                'AI大模型': notes.filter(n => n.category === 'AI大模型').length,
                '编程工具': notes.filter(n => n.category === '编程工具').length,
                '技术架构': notes.filter(n => n.category === '技术架构').length
            };

            Object.keys(counts).forEach(key => {
                const element = document.getElementById(`count-${key === 'AI大模型' ? 'ai' : key === '编程工具' ? 'coding' : key === '技术架构' ? 'arch' : 'all'}`);
                if (element) element.textContent = counts[key];
            });
        }

        // 生成标签云
        function generateTagCloud() {
            const allTags = {};
            notes.forEach(note => {
                note.tags.forEach(tag => {
                    allTags[tag] = (allTags[tag] || 0) + 1;
                });
            });

            const tagCloud = document.getElementById('tag-cloud');
            tagCloud.innerHTML = Object.entries(allTags)
                .sort(([,a], [,b]) => b - a)
                .slice(0, 15)
                .map(([tag, count]) => `
                    <span class="tag cursor-pointer px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded hover:bg-blue-100 hover:text-blue-800 transition-colors" onclick="filterByTag('${tag}')">
                        ${tag} (${count})
                    </span>
                `).join('');
        }

        // 渲染Markdown（简化版）
        function renderMarkdown(content) {
            return content
                .replace(/^# (.*$)/gm, '<h1 class="text-2xl font-bold mb-4">$1</h1>')
                .replace(/^## (.*$)/gm, '<h2 class="text-xl font-bold mb-3">$1</h2>')
                .replace(/^### (.*$)/gm, '<h3 class="text-lg font-bold mb-2">$1</h3>')
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                .replace(/\*(.*?)\*/g, '<em>$1</em>')
                .replace(/\`\`\`([\\s\\S]*?)\`\`\`/g, '<pre><code>$1</code></pre>')
                .replace(/\`(.*?)\`/g, '<code class="bg-gray-100 px-1 py-0.5 rounded text-sm">$1</code>')
                .replace(/\\n\\n/g, '</p><p>')
                .replace(/^(.+)$/gm, '<p>$1</p>');
        }

        // 导出笔记
        function exportNote() {
            if (!currentNote) return;

            const content = `# ${currentNote.title}\n\n**分类**: ${currentNote.category}\n**标签**: ${currentNote.tags.join(', ')}\n**创建时间**: ${formatDate(currentNote.createdAt)}\n**更新时间**: ${formatDate(currentNote.updatedAt)}\n\n---\n\n${currentNote.content}`;
            
            const blob = new Blob([content], { type: 'text/markdown' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${currentNote.title}.md`;
            a.click();
            URL.revokeObjectURL(url);
        }

        // 显示通知
        function showNotification(message) {
            const notification = document.createElement('div');
            notification.className = 'fixed top-20 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 transform translate-x-full transition-transform';
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.transform = 'translateX(0)';
            }, 100);
            
            setTimeout(() => {
                notification.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 3000);
        }

        // 格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            const now = new Date();
            const diffTime = Math.abs(now - date);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            
            if (diffDays === 1) return '今天';
            if (diffDays === 2) return '昨天';
            if (diffDays <= 7) return `${diffDays}天前`;
            
            return date.toLocaleDateString('zh-CN');
        }

        // 初始显示空状态
        showEmptyState();
    </script>
    <script src="api.js"></script>
</body>
</html>